package com.breeze.components.task.xxl.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.breeze.components.core.exception.CommonException;
import com.breeze.components.task.xxl.config.properties.XxlJobProperties;
import com.breeze.components.task.xxl.model.XxlJobGroup;
import com.breeze.components.task.xxl.service.JobGroupService;
import com.breeze.components.task.xxl.service.JobLoginService;
import jakarta.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

/**
 * 执行器任务处理实现类
 *
 * @author breeze
 */
@Service
@Slf4j
public class JobGroupServiceImpl implements JobGroupService {

  @Resource XxlJobProperties properties;

  @Resource private JobLoginService jobLoginService;

  @Override
  public List<XxlJobGroup> getJobGroup() {
    String url = properties.getAdminAddresses() + "/jobgroup/pageList";
    try {
      HttpResponse response =
          HttpRequest.post(url)
              .form("appname", properties.getAppName())
              .form("title", properties.getTitle())
              .cookie(jobLoginService.getCookie())
              .execute();
      JSONArray array = JSON.parseObject(response.body()).getJSONArray("data");
      return array.toJavaList(XxlJobGroup.class);
    } catch (Exception ex) {
      throw new CommonException("获取任务group失败");
    }
  }

  @Override
  public boolean autoRegisterGroup() {
    try {
      String url = properties.getAdminAddresses() + "/jobgroup/save";
      HttpRequest httpRequest =
          HttpRequest.post(url)
              .form("appname", properties.getAppName())
              .form("title", properties.getTitle());

      httpRequest.form("addressType", properties.getAddressType());
      if (properties.getAddressType().equals(1)) {
        if (Strings.isBlank(properties.getAddressList())) {
          throw new RuntimeException("手动录入模式下,执行器地址列表不能为空");
        }
        httpRequest.form("addressList", properties.getAddressList());
      }

      HttpResponse response = httpRequest.cookie(jobLoginService.getCookie()).execute();
      JSONObject jsonObject = JSON.parseObject(response.body());
      Integer code = jsonObject.getInteger("code");
      if (!Objects.equals(200, code)) {
        log.error(
            ">>>>>>>>>>> xxl-job auto register group fail!msg[{}]", jsonObject.getInteger("msg"));
        return false;
      }
      return true;
    } catch (Exception ex) {
      throw new CommonException("获取任务group失败");
    }
  }

  @Override
  public boolean preciselyCheck() {
    List<XxlJobGroup> jobGroup = getJobGroup();
    Optional<XxlJobGroup> has =
        jobGroup.stream()
            .filter(
                xxlJobGroup ->
                    xxlJobGroup.getAppname().equals(properties.getAppName())
                        && xxlJobGroup.getTitle().equals(properties.getTitle()))
            .findAny();
    return has.isPresent();
  }
}
